<?php

use think\Cache;
use think\Db;

// 异常错误报错级别,
error_reporting(E_ERROR | E_PARSE);

function C($name)
{
    $config = cache('systemConfig');
    if ($config) {
        $value = '';
        foreach ($config as &$v) {
            if ($v['name'] == $name) {
                $value = $v['output_value'];
                break;
            }
        }

        return $value;
    } else {
        $config = Db::name('config')->where(['name' => $name])->order('sort asc')->value('value');
        return $config;
    }
}

/**
 * 系统加密方法
 * @param string $data   要加密的字符串
 * @param int    $expire 过期时间 (单位:秒)
 * @return string
 */
function thinkEncrypt($data, $expire = 0)
{
    $key = md5('083d9a270e6e16b2fbb08d35067aae5f');
    $data = base64_encode($data);
    $x = 0;
    $len = strlen($data);
    $l = strlen($key);
    $char = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    $str = sprintf('%010d', $expire ? $expire + time() : 0);
    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
    }

    return str_replace('=', '', base64_encode($str));
}

/**
 * 系统解密方法
 * @param string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @return string
 */
function thinkDecrypt($data)
{
    $key = md5('083d9a270e6e16b2fbb08d35067aae5f');
    $x = 0;
    $data = base64_decode($data);
    $expire = substr($data, 0, 10);
    $data = substr($data, 10);
    if ($expire > 0 && $expire < time()) {
        return '';
    }
    $len = strlen($data);
    $l = strlen($key);
    $char = $str = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        } else {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }

    return base64_decode($str);
}

/**
 * 检查验证码
 * */
function checkVerify($code)
{
    $verify = new \think\captcha\Captcha();

    return $verify->check($code);
}

/**
 * 判断是否SSL协议
 * @return boolean
 */
function is_ssl()
{
    if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
        return true;
    } else if (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
        return true;
    }

    return false;
}

/**
 * 获取域名前缀
 * */
function getHost()
{
    $res = is_ssl();
    if ($res) {
        return 'https://' . $_SERVER['HTTP_HOST'];
    } else {
        return 'http://' . $_SERVER['HTTP_HOST'];
    }
}

/**
 * 按综合方式输出通信数据
 * @param integer $result 状态码
 * @param string  $msg    提示信息
 * @param array   $data   数据
 * @return string
 */
function apiReturn($result, $msg = '', $data = false)
{
    if (!is_numeric($result)) {
        return '';
    }

    return apiJson($result, $msg, $data);
}

/**
 * 按json方式输出通信数据
 * @param integer $result 状态码
 * @param string  $msg    提示信息
 * @param array   $data   数据
 * @return string
 */
function apiJson($result, $msg = '', $data = false)
{

    if (!is_numeric($result)) {
        return '';
    }

    if ($data > 0 || $data === []) {
        $message = [
            'result' => $result,
            'msg' => $msg,
            'data' => $data ? $data : []
        ];
    } else {
        $message = [
            'result' => $result,
            'msg' => $msg,
            'data' => $data ? $data : ''
        ];
    }

    echo json_encode($message, JSON_UNESCAPED_UNICODE);
    exit;
}

function httpsRequest($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

/**
 * 获取access_token
 * @param string $token_file_name token存储文件名
 * @param int    $type            1:公众号token，2：小程序token
 * @return string
 *  */
function get_access_token($token_file_name = 'access_token.json', &$count = 0)
{
    $config = [
        'appid' => C('XCX_APPID'),
        'secret' => C('XCX_SECRET'),
    ];

    // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
    $data = json_decode(get_php_file($token_file_name));
    if ($data->expires_time < time()) {
        // 如果是企业号用以下URL获取access_token
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $config['appid'] . "&secret=" . $config['secret'];
        $access_token_json = httpsRequest($url);
        $access_token = json_decode($access_token_json, true);
        $code = $access_token['errcode'] ? : 0;
        if ($code == 0) {
            $data->expires_time = time() + 3000;
            $data->access_token = $access_token;
            set_php_file($token_file_name, json_encode($data));

            $access_token = $access_token['access_token'];
        } else {
            if ($count < 3) {
                ++$count;
                get_access_token('access_token.json', $count);
            } else {
                unlink(RUNTIME_PATH . '/' . $token_file_name);
                apiReturn(2, $access_token['errmsg']);
            }
        }
    } else {
        $access_token = $data->access_token->access_token;
    }
    return $access_token;
}

function get_php_file($filename)
{
    if (!is_file(RUNTIME_PATH . '/' . $filename)) {
        $data['expires_time'] = 0;
        $data['jsapi_ticket'] = '';
        set_php_file($filename, json_encode($data));
    }
    return file_get_contents(RUNTIME_PATH . '/' . $filename);
}

function set_php_file($filename, $content)
{
    file_put_contents(RUNTIME_PATH . '/' . $filename, $content);
}

/**
 * 注册用户 及 绑定用户
 * @param string $unionid    unionid
 * @param string $up_user_id 分享人的用户id
 * @param array  $user_data  当前用户信息
 * @return array
 * */
function bindUserBak($unionid, $up_user_id, $user_data)
{
    $time = time();
    // 通过unionid查询当前用户是否存在
    $user_info = Db::name('user')->where(['unionid' => $unionid])->find();
    //    file_put_contents(RUNTIME_PATH . 'bindUser.txt', 'unionid：' . $unionid . '；up_user_id：' . $up_user_id . '；user_data：' . json_encode($user_data, JSON_UNESCAPED_UNICODE));
    if ($user_info) {
        if (empty($user_info['up_user_id'])) {
            // 当前用户没有上级，不可能再有上级用户
            $return_data = [
                'user_id' => $user_info['id'],
                'mobile' => $user_info['mobile'] ? : ''
            ];
            return $return_data;
        } else {
            if ($user_info['id'] != $up_user_id) {
                // 当前用户的上级用户id
                $up_up_user_id = Db::name('user')->where(['id' => $up_user_id])->value('up_user_id');

                /**
                 * 用户绑定：
                 * 条件一：用户存在，检测到没有上级
                 * 条件二：当前用户的上级用户id不是自己
                 * */
                if ($user_info['up_user_id'] == 0 && $up_up_user_id != $user_info['id']) {
                    $user_data['up_user_id'] = $up_user_id;
                    $user_data['update_time'] = $time;
                    // 绑定用户关系
                    $res = Db::name('user')->where(['unionid' => $unionid])->update($user_data);
                    if ($res) {
                        $return_user_id = $user_info['id'];
                        $return_mobile = $user_info['mobile'] ? : '';
                    } else {
                        $return_user_id = 0;
                        $return_mobile = '';
                    }
                } else {
                    $return_user_id = $user_info['id'];
                    $return_mobile = $user_info['mobile'] ? : '';
                }

                if ($return_user_id) createUserQr($return_user_id);

                Db::name('user')->where(['id' => $user_info['id']])->update($user_data);

                $return_data = [
                    'user_id' => $return_user_id,
                    'mobile' => $return_mobile ? : ''
                ];
                return $return_data;
            } else {
                // 自己扫自己的码，直接返回信息
                $return_data = [
                    'user_id' => $user_info['id'],
                    'mobile' => $user_info['mobile'] ? : ''
                ];
                return $return_data;
            }
        }
    } else {
        //注册用户信息 及 绑定
        $user_data['up_user_id'] = $up_user_id;
        $user_data['create_time'] = $time;

        $id = Db::name('user')->insertGetId($user_data);
        $return_user_id = $id;

        if ($return_user_id) createUserQr($return_user_id);

        $return_data = [
            'user_id' => $return_user_id,
            'mobile' => ''
        ];

        return $return_data;
    }
}

/**
 * 注册用户 及 绑定用户
 * @param string $openid     openid
 * @param string $up_user_id 分享人的用户id
 * @param array  $user_data  当前用户信息
 * @return array
 * */
function bindUser($openid, $up_user_id, $user_data)
{
    $time = time();

    // 通过unionid查询当前用户是否存在
    $user_info = Db::name('user')->where(['openid' => $openid])->find();
    if ($user_info) {
        // 老用户
        if (empty($user_info['username'])) Db::name('user')->where(['id' => $user_info['id']])->setField('username', $user_data['username']);
        if (empty($user_info['avatar'])) Db::name('user')->where(['id' => $user_info['id']])->setField('avatar', $user_data['avatar']);

        // 直接返回用户id和用户手机号
        $return_data = [
            'user_id' => $user_info['id'],
            'mobile' => $user_info['mobile'] ? : ''
        ];
        return $return_data;
    } else {
        // 新用户

        //注册用户信息 及 绑定
        $user_data['up_user_id'] = $up_user_id;
        $user_data['create_time'] = $time;

        $return_user_id = Db::name('user')->insertGetId($user_data);

        if ($return_user_id) createUserQr($return_user_id);

        $return_data = [
            'user_id' => $return_user_id,
            'mobile' => ''
        ];

        return $return_data;
    }
}


/**
 * 生成用户分享码（公众号二维码[带用户id]）
 * @param string $user_id 用户id
 * @return string
 * */
function createUserQr($user_id)
{
    $qr = Db::name('user')->where(['id' => $user_id])->value('qr');
    if ($qr == 0) {
        $access_token = get_access_token();

        $data = '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "' . $user_id . '"}}}';

        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $access_token;

        $res = httpsRequest($url, $data);
        $result = json_decode($res, true);
        $ticket = $result['ticket'];
        $img = file_get_contents('https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $ticket);

        $dir = './uploads/userQr/';
        if (!is_dir($dir)) mkdir($dir);

        $path = $dir . 'userQr_' . $user_id . '.jpg';

        $data = [
            'path' => substr($path, 1),
            'create_time' => time()
        ];
        $id = Db::name('picture')->insertGetId($data);

        if ($id) {
            file_put_contents($path, $img);

            Db::name('user')->where(['id' => $user_id])->setField('qr', $id);

            return $id;
        }
    }
}

/**
 * TODO: 待优化
 * 查询一个用户下的所有不同线路组合
 * 调用方法：getSonUserList($id, $data);
 * @param int   $user_id 用户id
 * @param array $data    返回数据
 * @param array $keys    临时变量
 * @return array
 * */
function getSonUserList($user_id, &$data = [], $keys = [])
{
    $user_list = Db::name('user')->field('id')->where(['up_user_id' => $user_id])->select();
    if ($user_list) {
        foreach ($user_list as $v) {
            $tmpKeys = $keys;
            $tmpKeys[] = $v['id'];
            getSonUserList($v['id'], $data, $tmpKeys);
        }
    } else {
        $data[] = $keys;
        return $data;
    }
}

/**
 * 根据图片id获取图片路径
 * */
function getPicture($id)
{
    if (preg_replace('/\D/s', '', $id) == $id) {
        //ID
        $info = Db::name('picture')->field('path')->where(['id' => $id])->find();
        if ($info) {
            return getHost() . $info['path'];
        } else {
            return '';
        }
    } else {
        //路径
        return $id;
    }
}

/**
 * 用户头像处理
 * @param int $avatar_id 用户头像ID 或 用户头像路径
 * @return string
 * */
function doAvatar($avatar_id)
{
    if (strlen($avatar_id) < 10) {
        //此时用户头像为修改之后的头像
        $avatar = getPicture($avatar_id);
    } else {
        $avatar = $avatar_id;
    }

    return $avatar ? $avatar : '';
}

/**
 * 多图处理
 * @param string $imgs    图片id集合
 * @param string $img_key 自定义图片路径下标
 * @return array
 * */
function doImgs($imgs, $img_key = 'path')
{
    $new_img_arr = [];
    if ($imgs) {
        $img_arr = explode(',', $imgs);

        if ($img_arr) {
            foreach ($img_arr as $k => &$v) {
                $new_img_arr[$k]['id'] = $v;
                $new_img_arr[$k][$img_key] = getPicture($v);
            }
        }
    }

    return $new_img_arr;
}

/**
 * 获取[规格-属性]数据
 * @param int $goods_id 商品id
 * @return array
 * */
function getSku($goods_id)
{
    if (!cache('sku_' . $goods_id)) {
        $sku_value_list = Db::name('sku_value')->where(['goods_id' => $goods_id])->select();

        //$skus_id_arr：所有属性的id集合
        $skus_id_arr = [];
        if ($sku_value_list) {
            foreach ($sku_value_list as &$val) {
                $val['img'] = getPicture($val['img']);

                $sku_id = explode('-', $val['sku_id']);
                if ($sku_id) {
                    foreach ($sku_id as &$value) {
                        if (!in_array($value, $skus_id_arr)) {
                            $skus_id_arr[] = $value;
                        }
                    }
                }
            }

            $parent_list = Db::name('sku')->distinct(true)->field('pid')->where(['id' => ['IN', $skus_id_arr]])->select();
            $parent_ids = array_column($parent_list, 'pid');
            if ($parent_ids) {
                $sku_list = Db::name('sku')->field('id,name title')->where(['id' => ['IN', $parent_ids]])->select();
                if ($sku_list) {
                    foreach ($sku_list as &$v) {
                        $child_list = Db::name('sku')->field('id,name title')->where(['pid' => $v['id']])->select();
                        if ($child_list) {
                            foreach ($child_list as &$val) {
                                $val['class'] = '';
                                $val['status'] = false;
                                foreach ($sku_value_list as &$value) {
                                    if (in_array($val['id'], explode('-', $value['sku_id'])) && $value['status']) {
                                        $val['status'] = true;
                                        break;
                                    }
                                }
                            }
                        } else {
                            $child_list = [];
                        }
                        $v['child'] = $child_list;
                    }
                } else {
                    $sku_list = [];
                }
            }
        } else {
            $sku_value_list = [];
        }

        $data = [
            'sku_list' => $sku_list,
            'sku_value_list' => $sku_value_list
        ];
        cache('sku_' . $goods_id, $data);
    } else {
        $data = cache('sku_' . $goods_id);
        // 获取最新库存
        if ($data['sku_value_list']) {
            foreach ($data['sku_value_list'] as &$v) {
                $stock = Db::name('sku_value')->where(['sku_id' => $v['sku_id'], 'goods_id' => $v['goods_id']])->value('stock');
                $v['stock'] = $stock;
            }
        }
    }

    return $data;
}

/**
 * 微信违规文字检测
 * */
function checkContent($content)
{
    if ($access_token = accessToken()) {
        $checkUrl = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' . $access_token;
        $arr = [
            'content' => $content
        ];

        $result = httpRequest($checkUrl, $arr, 'json');
        $result = json_decode($result, true);

        if ($result['errcode'] != 0) apiReturn(2, '检测到文字含违规内容，请重新编辑');
    } else {
        apiReturn(2, 'access_token获取失败');
    }
}

function accessToken()
{
    $appid = C('XCX_APPID');
    $secret = C('XCX_SECRET');
    $tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
    $tokenArr = file_get_contents($tokenUrl);
    $tokenArr = json_decode($tokenArr, true);

    return $tokenArr['access_token'];
}

function httpRequest($url, $data, $type)
{
    if ($type == 'json') {
        $headers = ["Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache"];
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
    } else {
        $headers = [];
    }
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    $output = curl_exec($curl);
    curl_close($curl);

    return $output;
}


/**
 * 一维数组去重
 * */
function a_array_unique($array)
{
    $out = [];
    foreach ($array as $key => $value) {
        if (!in_array($value, $out)) {
            $out[$key] = $value;
        }
    }
    return $out;
}

/**
 * 处理富文本信息
 * @param string $content 富文本内容
 * @return  string
 * */
function doEditorContent($content)
{
    return $content ? str_replace('<img src="', ' < img style = "width: 100%; height: auto" src = "' . getHost(), $content) : '';
}

/**
 * 格式化时间
 * @param int  $time 时间戳
 * @param date $date 时间格式
 * */
function timeFormat($time, $date = 'Y-m-d H:i:s')
{
    if ($time) {
        return date($date, $time);
    } else {
        return '';
    }
}

/**
 * @param array $sku_id 属性id集合
 * @return string
 * */
function getSkuName($sku_id)
{
    if ($sku_id) {
        $in_sku = implode(',', $sku_id);
        $order = ' field (id, ' . $in_sku . ' ) ';
        $sql = 'SELECT `name` FROM `shop_sku` WHERE `id` IN(' . $in_sku . ') ORDER BY ' . $order;
        $sku_list = Db::query($sql);

        return $sku_list;
    } else {
        return '';
    }
}


/**
 * 获取首字母
 * @param string $str 汉字字符串
 * @return string 首字母
 */
function getInitials($str)
{
    if (empty($str)) {
        return '';
    }
    $fchar = ord($str{0});
    if ($fchar >= ord('A') && $fchar <= ord('z')) {
        return strtoupper($str{0});
    }

    $s1 = iconv('UTF-8', 'gb2312', $str);
    $s2 = iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 && $asc <= -20284) {
        return 'A';
    }

    if ($asc >= -20283 && $asc <= -19776) {
        return 'B';
    }

    if ($asc >= -19775 && $asc <= -19219) {
        return 'C';
    }

    if ($asc >= -19218 && $asc <= -18711) {
        return 'D';
    }

    if ($asc >= -18710 && $asc <= -18527) {
        return 'E';
    }

    if ($asc >= -18526 && $asc <= -18240) {
        return 'F';
    }

    if ($asc >= -18239 && $asc <= -17923) {
        return 'G';
    }

    if ($asc >= -17922 && $asc <= -17418) {
        return 'H';
    }

    if ($asc >= -17417 && $asc <= -16475) {
        return 'J';
    }

    if ($asc >= -16474 && $asc <= -16213) {
        return 'K';
    }

    if ($asc >= -16212 && $asc <= -15641) {
        return 'L';
    }

    if ($asc >= -15640 && $asc <= -15166) {
        return 'M';
    }

    if ($asc >= -15165 && $asc <= -14923) {
        return 'N';
    }

    if ($asc >= -14922 && $asc <= -14915) {
        return 'O';
    }

    if ($asc >= -14914 && $asc <= -14631) {
        return 'P';
    }

    if ($asc >= -14630 && $asc <= -14150) {
        return 'Q';
    }

    if ($asc >= -14149 && $asc <= -14091) {
        return 'R';
    }

    if ($asc >= -14090 && $asc <= -13319) {
        return 'S';
    }

    if ($asc >= -13318 && $asc <= -12839) {
        return 'T';
    }

    if ($asc >= -12838 && $asc <= -12557) {
        return 'W';
    }

    if ($asc >= -12556 && $asc <= -11848) {
        return 'X';
    }

    if ($asc >= -11847 && $asc <= -11056) {
        return 'Y';
    }

    if ($asc >= -11055 && $asc <= -10247) {
        return 'Z';
    }

    return null;
}

/**
 * 获取省id
 * @param string $province_name 省名称
 * @param int    $province_code 微信省id
 * @return int
 * */
function getProvinceId($province_name, $province_code = '')
{
    $province_id = Db::name('province')->where(['name' => $province_name])->value('province_id');
    if ($province_id) {
        return $province_id;
    } else {
        if (empty($province_code)) return '';

        $data = [
            'name' => $province_name,
            'province_id' => $province_code,
            'sp' => getInitials($province_name)
        ];
        Db::name('province')->insert($data);

        return $province_code;
    }
}

/**
 * 获取省名称
 * @param int $province_id 省id
 * @return string
 * */
function getProvinceName($province_id)
{
    $name = Db::name('province')->where(['province_id' => $province_id])->value('name');

    return $name ? $name : '';
}

/**
 * 获取市id
 * @param string $province_name 省名称
 * @param string $city_name     市名称
 * @param int    $province_code 微信省id
 * @param int    $city_code     微信市id
 * @return int
 * */
function getCityId($province_name, $city_name, $province_code = '', $city_code = '')
{
    $province_id = getProvinceId($province_name, $province_code);

    if (empty($province_id)) return '';

    // 最后一个字符
    $last_str = mb_substr($city_name, -1, 1, "utf-8");
    $city_name = in_array($last_str, ['市', '省']) ? str_replace($last_str, '', $city_name) : $city_name;
    $city_id = Db::name('city')->where(['province_id' => $province_id, 'name' => ['like', $city_name . '%']])->value('city_id');

    if ($city_id) {
        return $city_id;
    } else {
        if (empty($province_code) || empty($city_code)) return '';

        $data = [
            'city_id' => $city_code,
            'name' => $city_name,
            'province_id' => $province_id,
            'sp' => getInitials($city_name)
        ];
        Db::name('city')->insert($data);

        return $city_code;
    }

}

/**
 * 获取市名称
 * @param int $city_id 市id
 * @return string
 * */
function getCityName($city_id)
{
    $name = Db::name('city')->where(['city_id' => $city_id])->value('name');

    return $name ? $name : '';
}

/**
 * 获取区id
 * @param string $province_name 省名称
 * @param string $city_name     市名称
 * @param string $area_name     区名称
 * @param int    $province_code 微信区id
 * @param int    $city_code     微信市id
 * @param int    $area_code     微信区id
 * @return int
 * */
function getAreaId($province_name, $city_name, $area_name, $province_code = '', $city_code = '', $area_code = '')
{
    $city_id = getCityId($province_name, $city_name, $province_code, $city_code);

    // 最后一个字符
    $last_str = mb_substr($area_name, -1, 1, "utf-8");
    $area_name = in_array($last_str, ['市', '区', '县']) ? str_replace($last_str, '', $area_name) : $area_name;
    $area_id = Db::name('area')->where(['city_id' => $city_id, 'name' => ['like', $area_name . '%']])->value('area_id');

    if ($area_id) {
        return $area_id;
    } else {
        if (empty($province_code) || empty($city_code) || empty($area_code)) return '';

        $data = [
            'area_id' => $area_code,
            'name' => $area_name,
            'city_id' => $city_id
        ];
        Db::name('area')->insert($data);
        return $area_code;
    }
}

/**
 * 获取区名称
 * @param int $area_id 区id
 * @return string
 * */
function getAreaName($area_id)
{
    $name = Db::name('area')->where(['area_id' => $area_id])->value('name');

    return $name ? $name : '';
}

/**
 * 隐藏手机号
 * @param string $tel 手机号
 * @return string
 * */
function hideMobile($tel)
{
    return $tel ? substr_replace($tel, '****', 3, 4) : '';
}

/**
 * 处理会员等级
 * 1：游客，2：vip，3：社区服务站，4：县区服务站，5：城市服务站
 * */
function doUserLevel($level)
{
    switch ($level) {
        case 2:
            return 'VIP';
            break;
        case 3:
            return '社区服务站';
            break;
        case 4:
            return '县区服务站';
            break;
        case 5:
            return '城市服务站';
            break;
        default:
            return '游客';
            break;
    }
}

/**
 * 通过用户id集合获取用户名
 * */
function getUsers($user_ids)
{
    if ($user_ids) {
        $user_list = Db::name('user')->field('username')->where(['id' => ['IN', $user_ids]])->select();

        return $user_list ? implode('，', array_column($user_list, 'username')) : '';
    } else {
        return '';
    }
}

/**
 * 获取某个用户的所有上级用户id
 * @param int $user_id 用户id
 * @param string
 * */
function getAllUpUserIds($user_id, &$user_ids = [])
{
    $up_user_id = Db::name('user')->where(['id' => $user_id])->value('up_user_id');
    if ($up_user_id) {
        $user_ids[] = $up_user_id;
        getAllUpUserIds($up_user_id, $user_ids);
    }
}

/**
 * 某个用户的级别变更需要将其所有上级都加入到用户升级的任务计划
 * @param int  $user_id   用户id
 * @param bool $insert_me 是否将自己也加入到任务中
 * */
function addAllUpUserToUpPlan($user_id = 0, $insert_me = false)
{
    if ($user_id) {
        getAllUpUserIds($user_id, $up_user_ids);
        if ($up_user_ids) {
            $execute_date = date('Y-m-d', strtotime("+1 day"));

            if ($insert_me) {
                $plan_data[] = [
                    'user_id' => $user_id,
                    'type' => 1,
                    'execute_date' => $execute_date
                ];
            } else {
                $plan_data = [];
            }
            foreach ($up_user_ids as &$v) {
                $plan_data[] = [
                    'user_id' => $v,
                    'type' => 1,
                    'execute_date' => $execute_date
                ];
            }
            Db::name('plan')->insertAll($plan_data);
        }
    }
}

/**
 * 处理订单状态
 * @param int $status 订单状态
 * @return string
 * */
function doOrderStatus($status)
{
    switch ($status) {
        case 1:
            $desc = '待付款';
            break;
        case 2:
            $desc = '待发货';
            break;
        case 3:
            $desc = '待收货';
            break;
        case 4:
            $desc = '待评价';
            break;
        case 5:
            $desc = '已完成';
            break;
        case 7:
            $desc = '售后中';
            break;
        case 8:
            $desc = '售后完成';
            break;
        case 10:
            $desc = '已取消';
            break;
    }
    return $desc;
}

/**
 * 处理档数
 * @param string $gear 档数
 * @return string
 * */
function doGear($gear)
{
    switch ($gear) {
        case 'first_gear':
            $desc = '一档';
            break;
        case 'second_gear':
            $desc = '二档';
            break;
        case 'third_gear':
            $desc = '三挡';
            break;
    }

    return $desc;
}

/**
 * 发送微信公众号模板消息
 * @param string $openid 公众号openid
 * @param array  $msg    消息内容
 * @param string $type   消息类型：1：直推比例分佣，2：级差比例分佣，3：服务津贴，4：购物收益抵扣，5：收益提现，6：销售奖励月结，7：退休基金月结，8：收益提现失败返还收益，9：区域门店补贴月结，10：奖励收益，11，惩罚收益，12：购物抵扣收益退款
 * @param string $path   小程序路径
 * */
function sendWxTemplateNotice($openid, $msg, $type, $page = '')
{
    $access_token = get_access_token();

    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;

    switch ($type) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 6:
        case 7:
        case 9:
        case 10:
        case 11:
        case 12:
            $template_id = 'hfRL9eI5hfWwe_pgksT3KB3gcNO7e3eXNijsyFfKjgo';
            break;
        case 5:
        case 8:
            $template_id = 'HZOBcTpoczFYvS1VIIti8ZbMxpL5feWN8nX9zAdSMwQ';
            break;
    }

    $data = [
        'touser' => $openid,
        'template_id' => $template_id,
        'topcolor' => '#FF0000',
        'data' => $msg
    ];

    if ($page) {
        $data['miniprogram']['appid'] = C('XCX_APPID');
        $data['miniprogram']['pagepath'] = $page;
    }


    $data = json_encode($data, JSON_UNESCAPED_UNICODE);

    httpsRequest($url, $data);
}

/**
 * 获取用户当前剩余可用收益
 * @param int $user_id 用户id
 * @param float
 * */
function userProfit($user_id)
{
    $all_profit = Db::name('user')->where(['id' => $user_id])->value('all_profit');
    return sprintf('%.2f', $all_profit);
}

/**
 * 统计各级别有多少人
 * */
function levelCount($level)
{
    $count = Db::name('user')->where(['level' => $level])->count();
    return $count;
}

/**
 * 设置显示多少字符
 * @param string $str 字符串
 * @param int    $len 显示字符长度
 * @return string
 * */
function cutSubstr($str, $len = 8)
{
    if (mb_strlen($str) > $len) {
        $str = mb_substr($str, 0, $len) . '...';
    }
    return $str;
}

/**
 * 处理用户昵称显示
 * @param string $username 用户昵称
 * @return string
 * */
function cutUsername($username)
{
    $strlen = mb_strlen($username, 'utf-8');

    if ($strlen == 1) {
        $result = $username;
    } else {
        $firstStr = mb_substr($username, 0, 1, 'utf-8');
        $lastStr = mb_substr($username, -1, 1, 'utf-8');
        $result = ($strlen == 2) ? $firstStr . str_repeat('*', mb_strlen($username, 'utf-8') - 1) : $firstStr . str_repeat('*', $strlen - 2) . $lastStr;
    }

    return $result;
}

/**
 * 生成订单号
 * */
function createOrderSn()
{
    $order_sn = 'D' . date('y') . date('m') . date('d') . date('H') . date('i') . rand(1000, 9999);
    $count = Db::name('order')->where(['order_sn' => $order_sn])->count();
    if ($count > 0) {
        createOrderSn();
    } else {
        return $order_sn;
    }
}

/**
 * 获取某天某种收益的总和
 * @param string $date 日期
 * @param int    $type 类型：1：直推比例分佣，2：级差比例分佣，3：服务津贴，4：购物收益抵扣，5：收益提现，6：销售奖励月结，7：退休基金月结，8：收益提现失败返还收益，9：区域门店补贴月结，10：奖励收益，11，惩罚收益
 * @return float
 * */
function dayAllProfit($date, $type)
{
    if ($date) {
        $start_time = strtotime($date);
        $end_time = $start_time + 60 * 60 * 24 - 1;

        $where['type'] = $type;
        $where['status'] = ['neq', -1];
        $where['create_time'] = ['between', [$start_time, $end_time]];

        $all_profit = Db::name('profit')->where($where)->sum('price');
        return sprintf('%.2f', $all_profit);
    } else {
        return '0.00';
    }
}

/**
 * 获取某用户某天某种收益的总和
 * @param int    $user_id 用户id
 * @param string $date    日期
 * @param int    $type    类型：1：直推比例分佣，2：级差比例分佣，3：服务津贴，4：购物收益抵扣，5：收益提现，6：销售奖励月结，7：退休基金月结，8：收益提现失败返还收益，9：区域门店补贴月结，10：奖励收益，11，惩罚收益
 * @return float
 * */
function userAllProfit($user_id, $date, $type)
{
    if ($date) {
        $start_time = strtotime($date);
        $end_time = $start_time + 60 * 60 * 24 - 1;

        $where['user_id'] = $user_id;
        $where['type'] = $type;
        $where['status'] = ['neq', -1];
        $where['create_time'] = ['between', [$start_time, $end_time]];

        $all_profit = Db::name('profit')->where($where)->sum('price');
        return sprintf('%.2f', $all_profit);
    } else {
        return '0.00';
    }
}

/**
 * 获取用户层级数
 * @param int $user_id     上级用户id
 * @param int $son_user_id 下级用户id
 * @return int
 * */
function getTreeCount($user_id, $son_user_id, &$count = 0)
{
    if ($user_id == $son_user_id) {
        return $count == 0 ? '' : $count;
    } else {
        ++$count;
        $up_user_id = Db::name('user')->where(['id' => $son_user_id])->value('up_user_id');
        if ($up_user_id == $user_id) {
            return $count;
        } else {
            getTreeCount($user_id, $up_user_id, $count);
        }
    }
}

/**
 * 获取二维数组的key
 * */
function getUniqueArrayKeys($array)
{
    $keys = array_keys($array);
    return $keys;
}